package searchEngine;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.Map.Entry;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class SearchEngineServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp){
	
	}
	public void doPost(HttpServletRequest req, HttpServletResponse resp){
		
		try {
			if(req.getCharacterEncoding() == null)
				   req.setCharacterEncoding("ISO-8859-1");
			String searchExpr = req.getParameter("searchExpr");
			String separator = req.getParameter("separator");
			if (separator==null) separator = System.getProperty("line.separator");
			String URL = req.getParameter("url");
			if(searchExpr.length()>3 && URL.length()>3){
				String[] stringUrlList = URL.split("\n");
				if(stringUrlList.length>1){
					HashSet<URL> urlList = new HashSet<URL>();
					for(String s: stringUrlList){ 
						try {
							urlList.add(new URL(s));
						}catch(MalformedURLException e){
							resp.getWriter().println("Exception:" + e.getMessage().toString()+ " caused by: \n" + searchExpr);
						}
					}
					Map<URL, StringBuilder> searchResults = SearchEngine.search(searchExpr, urlList, separator);
					Set<URL> keyset = searchResults.keySet();
					for (URL key : keyset) {
						resp.getWriter().println(key+" : "+searchResults.get(key));
					}
				}else{
					resp.getWriter().println(SearchEngine.search(searchExpr, URL, separator));
				}

			}else resp.getWriter().println("The search criterions are invalid.");	
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

}
